package com.tarena.lbs.activity.consumer;


import com.rabbitmq.client.Channel;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.serializer.MessageSerializer;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.constant.AmqpDeclareConst;
import com.tarena.lbs.common.event.LocationEvent;
import com.tarena.lbs.coupon.api.CouponApi;
import com.tarena.lbs.coupon.api.pojo.param.UserCouponsParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;


/**
 * 用户位置信息消费者
 * 消费用户位置信息 实现自动营销
 */
@Slf4j
@Component
public class StoreLocationConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MessageSerializer<LocationEvent> messageSerializer;

    @DubboReference
    private CouponApi couponApi;

    @Autowired
    private ActivityService activityService;

    @RabbitListener(queues = {AmqpDeclareConst.NEAR_STORES_QUEUE})
    public void consume(Message message, Channel channel) throws BusinessException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //1.解析消息
        try {
            LocationEvent event = messageSerializer.deserialize(message.getBody(), LocationEvent.class);
            log.info("[Consumer] 收到用户位置信息：{}", event);
            List<ActivityPO> activityPOs = activityService.getActivityListByStoreId(event.getStoreId());
            log.info("[Consumer] 获取商家活动列表：{}", activityPOs);
            for (ActivityPO activityPO : activityPOs) {
                //1.判断活动是否可见
                if (activityService.activityVisible(event.getUserId(), activityPO.getId())) {
                    //2.发送优惠券
                    UserCouponsParam param = new UserCouponsParam();
                    param.setUserId(event.getUserId());
                    param.setCouponId(Integer.valueOf(activityPO.getRewardCouponId()));
                    param.setActivityId(activityPO.getId().intValue());
                    param.setShopId(event.getStoreId());
                    param.setReceiveChannel(1);
                    log.info("[Consumer] 发送优惠券：{}", param);
                    couponApi.receiveCoupon(param);
                }
            }
        } catch (Exception e) {
            log.error("消息处理失败", e);
            // 在自动确认模式下，抛出异常会导致消息重新入队
            throw new RuntimeException("消息处理失败", e);
        }
    }
}
